import datastructure.linklist.ListNode;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/14 10:21
 * @description:
 */
public class Solution2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode dummy = new ListNode(-1);
        ListNode p3 = dummy;
        int carry = 0;
        while (p1 != null || p2 != null) {
            int a = p1 != null ? p1.val : 0;
            int b = p2 != null ? p2.val : 0;
            int sum = (a + b + carry) % 10;
            carry = (a + b + carry) / 10;
            p3.next = new ListNode(sum);
            p3 = p3.next;
            if (p1 != null) {
                p1 = p1.next;
            }
            if (p2 != null) {
                p2 = p2.next;
            }
        }
        if(carry!=0){
            p3.next = new ListNode(carry);
            p3 = p3.next;
        }
        return dummy.next;
    }

    public static void main(String[] args) {
        Solution2 solution = new Solution2();
        ListNode l1 = ListNode.arrayToList(new int[]{2, 4, 3});
        ListNode l2 = ListNode.arrayToList(new int[]{5, 6, 4});
        ListNode head = solution.addTwoNumbers(l1, l2);
        ListNode.printList(head);
    }
}
